<script setup>
import OSS from 'ali-oss'
import { onMounted, ref } from 'vue'

// 创建OSS客户端
// const client = new OSS({
//   region: 'oss-cn-chengdu',
//   accessKeyId: 'LTAI5tKsESaCVvxSMvZb4vCb',
//   accessKeySecret: 'wLzCbAtNyQlJ6PZX5J2LAFCZrYFce7',
//   bucket: 'one-byte'
// })

const client = new OSS({
  region: 'oss-cn-chengdu',
  accessKeyId: 'LTAI5tCLrxMDGqt9c5du8HnB',
  accessKeySecret: 'AYFdH33B7qS4eLuekYCdsXdV9AKYZq',
  bucket: 'world-card'
})

const videoUrl = ref('')
const videoRef = ref(null) // 添加视频元素的引用
const isPlaying = ref(true) // 添加播放状态控制

const CACHE_KEY = 'random_video_cache'
const CACHE_EXPIRY_KEY = 'random_video_expiry'
const CACHE_DURATION = 60 * 1000 // 10秒的毫秒数 测试

// 处理视频点击事件
const handleVideoClick = () => {
  if (videoRef.value) {
    if (isPlaying.value) {
      videoRef.value.pause()
    } else {
      videoRef.value.play()
    }
    isPlaying.value = !isPlaying.value
  }
}

// 获取随机视频
const getRandomVideo = async () => {
  try {
    // 列出video目录下的所有文件
    const result = await client.list({
      prefix: 'video/',
      delimiter: '/'
    })
    if (result.objects && result.objects.length > 0) {
      // 随机选择一个视频
      const randomIndex = Math.floor(Math.random() * result.objects.length)
      const videoPath = result.objects[randomIndex].name
      // const url = `http://oss.lllll.online/${videoPath}`
      // const url = `http://oss-cn-chengdu.aliyuncs.com/${videoPath}`
      const url = `https://www.rccy.live/${videoPath}`
      
      // 缓存视频URL和过期时间
      localStorage.setItem(CACHE_KEY, url)
      localStorage.setItem(CACHE_EXPIRY_KEY, String(Date.now() + CACHE_DURATION))
      
      return url
    }
  } catch (error) {
    console.error('获取视频列表失败:', error)
  }
  return null
}

// 检查缓存是否有效
const checkCache = () => {
  const cachedUrl = localStorage.getItem(CACHE_KEY)
  const expiryTime = localStorage.getItem(CACHE_EXPIRY_KEY)
  
  if (cachedUrl && expiryTime) {
    if (Date.now() < Number(expiryTime)) {
      return cachedUrl
    }
  }
  return null
}

// 初始化视频
const initVideo = async () => {
  const cachedVideo = checkCache()
  if (cachedVideo) {
    videoUrl.value = cachedVideo
  } else {
    const newVideo = await getRandomVideo()
    if (newVideo) {
      videoUrl.value = newVideo
    }
  }
}

onMounted(() => {
  initVideo()
})
</script>

<template>
  <div class="video-container">
    <video
      v-if="videoUrl"
      ref="videoRef"
      :src="videoUrl"
      class="fullscreen-video"
      autoplay
      playsinline
      webkit-playsinline
      x5-video-player-type="h5"
      x5-video-player-fullscreen="true"
      x5-video-orientation="portraint"
      muted
      loop
      @click="handleVideoClick"
    ></video>
  </div>
</template>

<style lang="scss" scoped>
.video-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.fullscreen-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer; // 添加鼠标指针样式
}
</style>
